---
title: "Deconstruction Wood Sensitivity Analysis"
subtitle: "An evaluation of deconstruction salvage data using OSU maximum softwood density factor"
author:
- Andey Nunes, MS
- Research Analyst 2
- Oregon DEQ
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
  html_document:
    df_print: paged
    toc: yes
    toc_depth: '3'
  word_document:
    toc: yes
    toc_depth: '3'
---

```{r setup, echo=F, include = F}
# create a list of packages to be installed and active (required) for use in the notebook and resulting reports
packages <- c("corrplot", "fBasics", "ggrepel", "ggthemes", "grDevices", "knitr", "rstudioapi", "scales", "tidyverse")

# set defalut code chunks to "echo=TRUE" to display the code chunk inline with the narrative text; and report numbers to a default of three significant digits.
knitr::opts_chunk$set(echo = FALSE)
options(digits = 3)
options(scipen = 999)

lapply(packages, require, character.only = T)
options(xtable.comment = F)
rm(packages)

# DEQ color palette for graphics using approximate match colors from grDevices package
DEQ_pal <- c('aquamarine4', 'steelblue4', 'lightseagreen', 'yellowgreen', 'darkorange1',
            'darkseagreen3', 'slateblue1', 'powderblue', 'khaki', 'lightsalmon',
            'seagreen4', 'deepskyblue4', 'darkslateblue', 'magenta4', 'palegreen4',
            'cyan4', 'goldenrod2', 'indianred3', 'seagreen')

# specifications for saving graphics files
graph_path <- file.path("graphs/")
width <- 12
height <- 8
```

# Introduction

The 2018 Deconstruction Data Analysis used project data from residential single family homes removed under a City of Portland Deconstruction permit. The goal of the data analysis is to quantify the net environmental benefits resulting from avoided disposal of materials due to salvage/reuse (measured as Global Warming Potential and Primary Energy Demand impacts). 

# Data Sources and Description

Project specific materials data originated from the following (pdf, png, or jpeg) receipts and inventory sources:
*  Receipts from dropbox and recycling haulers (pdf and pictures of printouts)
*  Pictures of handwritten sale or donation slips
*  Inventory forms and lists (as pdf)

All receipts were summarized in an excel spreadsheet, then reported quantities were converted to kilograms of materials. Energy and carbon impacts are calculated on the weight of materials specific to the end-of-life fate (or disposition), which is categorized as: reused, recycled, burned for energy recovery, or landfilled. Materials salvaged were treated as reused in the deconstruction scenario, while for the demolition equivalent scenario, those materials were assigned a disposition in accordance with the Metro region wide waste composition data. Materials disposed in dropboxes were standardized by material type and percentage of the dropbox weight and then assigned the waste composition dispositions under both the deconstruction and demolition scenarios.

```{r data import and reformat}
# download house data
house_weight <- read.csv("intermediary/house_weight.csv", stringsAsFactors = F)
# reformat coded data as character
house_weight$project <- as.character(house_weight$project)
house_weight$contractor <- as.character(house_weight$contractor)

# load final net impacts summary and remove index
final_impact_summary <- read.csv("intermediary/final_impact_summary.csv", stringsAsFactors = F) %>%
   select(-1)

# load material weight detail data, remove index, and filter out dropbox info
salvage_material_weight <- read.csv("intermediary/decon_material_weight.csv", stringsAsFactors = F) %>%
   select(-1) %>% filter(deconMaterialName != "dropbox")

# reformat coded data as character
salvage_material_weight$project <- as.character(salvage_material_weight$project)
salvage_material_weight$contractor <- as.character(salvage_material_weight$contractor)

# download all project impact data and remove index
project_impact_data <- read.csv("intermediary/final_complete_data_all_scenario_impacts.csv", stringsAsFactors = F) %>%
   select(-1)
# reformat coded data as character
project_impact_data$project <- as.character(project_impact_data$project)
project_impact_data$contractor <- as.character(project_impact_data$contractor)
# replace scenario field info with full names for charts
project_impact_data$scenario <- str_replace_all(project_impact_data$scenario, "decon", "deconstruction")
project_impact_data$scenario <- str_replace_all(project_impact_data$scenario, "demo", "demolition")

# reshape data for summarizing and chart usage
gathered_impacts <- project_impact_data %>%
   gather(`material_impacts`, `site_transport_impact`, `EOL_transport_impact`, key = "impact_origin", value = "impact")

```

## Data Set Description


```{r data summary}
ave_house_size <- summarise(house_weight, avg_sq_ft = mean(house_size))
total_house_size <- summarise(house_weight, total_sq_ft = sum(house_size)) # total sq_Ft from all projects
number_of_houses <- as.integer(length(house_weight$project))

house_weight_US_units <- house_weight %>%
   transmute(
      salvage = total_salvage_quantity  * 2.20462,
      salvage_quantity_units = "lbs",
      dropbox = total_dropbox_quantity * 2.20462,
      dropbox_units = "lbs",
      total_house_weight = salvage + dropbox,
      total_house_weight_units = "lbs",
      percent_salvaged = round(salvage / total_house_weight * 100)
   ) %>%
   add_column(project = house_weight$project) %>%
   add_column(contractor = house_weight$contractor) %>%
   add_column(house_age = house_weight$house_age) %>%
   add_column(house_size = house_weight$house_size) %>%
   mutate(est_weight = house_size * 50) %>%
   mutate(missing_house_est = est_weight - total_house_weight) %>%
   mutate(percent_missing = missing_house_est / est_weight * 100)

# added comparison weight column to detect anomalies in total house weight compared to EPA/METRO estimate house weight
# based on 50 lbs per sq_ft assumption of residential home weight without concrete foundation
# https://www.epa.gov/sites/production/files/2016-03/documents/charact_bulding_related_cd.pdf
# TABLE 5 p27



 
# summary data needed for pie chart
options(digits = 2)
house_weight_summary <- house_weight %>%
   summarise_at(c("total_salvage_quantity", "total_dropbox_quantity"), sum ) %>%
   rename(salvage = total_salvage_quantity) %>%
   rename(dropbox = total_dropbox_quantity) %>%
   gather(key = "material", value = "weight_kg") %>%
   mutate(lbs = as.integer(weight_kg * 2.20462)) %>%
   mutate(per_average_project = lbs/number_of_houses) #%>%
   #mutate(city_wide = per_average_project * 324)
```


# Results


#### Projects/Houses
There are `r length(house_weight$project)` projects in the data set.  The average house was `r mean(house_weight$house_age)` years old, roughly `r mean(house_weight$house_size)` square feet, and yielded approximately `r house_weight_summary[1,4]` lbs of salvage materials. 


**Figure 4**

```{r pie}
# pie
ggplot(house_weight_summary, aes(x = "", y = weight_kg, fill = material)) +
   geom_bar(width = 1, stat = "identity", show.legend = F) +
   coord_polar(theta = "y", start = 0) +
   scale_y_continuous(breaks = 6) +
   scale_fill_manual(values = DEQ_pal[2:3]) +
   labs(x = "", y = "") + # use this line to make a pie chart with no title/labels
   # labs(x = "", y = "", fill = "material", title = "Deconstruction projects: overall material yield total", subtitle = "proportion of salvage and disposal by weight") +
   geom_text(aes(label = scales::percent(weight_kg/sum(weight_kg))), color = "grey100", size = 7, vjust = -2) +
   geom_text(aes(label = material), color = "grey100", size = 5, vjust = -5 ) +
   geom_text(aes(label = paste0("(", format(per_average_project, digits = 3, big.mark = ",", big.interval = 3L), " pounds)")), color = "grey100", size = 5, vjust = -1 ) +
   theme_tufte()

ggsave(filename = "pie_salvage_dropbox.png", device = "png", path = graph_path, units = "in")
```


**Figure 5** – total weights of each material category SALVAGED, ranked from highest to lowest, with labels (material name and total kg)



```{r salvage wt by material category}

# sum salvage quantity by material name for average project and convert to US lbs
salvage_material_weight_summary <- salvage_material_weight %>%
   group_by(deconMaterialName) %>%
   summarise(quantity = sum(converted_quantity)) %>%
   mutate(per_project_quantity = quantity/number_of_houses * 2.20462)
# save data table
write.csv(salvage_material_weight_summary, "output/average home salvage yield.csv")
# make horizontal bar chart of weight by material for the average house
ggplot(salvage_material_weight_summary, aes(reorder(deconMaterialName, per_project_quantity) , per_project_quantity)) +
   geom_bar(stat = "identity", fill = DEQ_pal[3]) +
   geom_text(aes(label = format(per_project_quantity, digits = 2, big.mark = ",", big.interval = 3L)), size = 3.5, hjust = -0.1, show.legend = F ) +
   scale_y_continuous(limits = c(0, 10000), labels = comma ) +
   labs(x = "material name", y = "average home salvage yield (lbs)") +
   coord_flip() +
   theme_tufte() +
   theme(axis.text = element_text(size = 12),
         axis.title = element_text(size = 12,face = "bold"))
   # ggtitle("Salvage weight (kg) by material type")
   # 

ggsave(filename = "salvage_by_material.png", device = "png", path = graph_path, units = "in")
```




**Figure 6** total weight of material disposed, demo only, grouped by the 4 broad categories (recoverable wood, other, non-recoverable wood, metal). 

```{r decon vs demo disposal}
# summarise dropbox weight by material type for the average house
decon_disposal <- project_impact_data %>%
   filter(scenario == "deconstruction") %>%
   filter(disposition != "reuse") %>%
   filter(disposition != "none") %>%
   group_by(SimpleEOLname) %>%
   summarise(kg = sum(quantity)/2) %>%
   mutate(lbs_per_project = kg * 2.20462 / number_of_houses)
# make another horizontal bar chart for the average project dropbox materials
ggplot(decon_disposal, aes(x = SimpleEOLname, y = lbs_per_project)) +
   geom_bar(stat = "identity", fill = DEQ_pal[2]) +
   geom_text(aes(label = format(lbs_per_project, digits = 2, big.mark = ",", big.interval = 3L)), size = 3.5, hjust = -0.1, show.legend = F ) +
   scale_y_continuous(limits = c(0, 14000), labels = comma ) +
   labs(x = "material", y = "average deconstructed home dropbox weight composition (lbs)") +
   coord_flip() +
   theme(axis.text = element_text(size = 12),
         axis.title = element_text(size = 12,face = "bold")) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12),
         axis.title = element_text(size = 12,face = "bold"))

ggsave(filename = "dropbox_by_material_type.png", device = "png", path = graph_path, units = "in")
```



## Carbon and Energy main impacts tables (Report Section 4.2)

```{r per home based impact contribution breakdown}

# reshape/configure the data to produce tables and requested graphics
reshaped_per_home_final_impact <- final_impact_summary %>%
   select(c("scenario", "impact_origin", "per_home_impact", "impact_units")) %>%
   spread(key = impact_origin, value = per_home_impact) %>%
   rename(materials = material_impacts) %>%
   rename(worker_transport = workers) %>%
   rename(equipment_use = equipment) %>%
   mutate(material_transport = EOL_transport_impact + site_transport_impact) %>%
   mutate(total = materials + material_transport + worker_transport + equipment_use)

reshaped_per_home_final_impact$scenario <- str_replace_all(reshaped_per_home_final_impact$scenario, "decon", "Deconstruction")

reshaped_per_home_final_impact$scenario <- str_replace_all(reshaped_per_home_final_impact$scenario, "demo", "Demolition")   
```


```{r per home based impact contribution report tables}
gathered__per_home_final_impact <- reshaped_per_home_final_impact %>%
   select(-material_transport) %>% # don't need this category as it is the sum of the site & EOL transport
   gather(`materials`, `site_transport_impact`, `EOL_transport_impact`, `worker_transport`, `equipment_use`, `total`, key = "impact_origin", value = "impact_value") %>%
   # reformat the field entries for impact_origin
   mutate(impact_type = case_when(impact_origin == "materials" ~ "Material impacts",
                                  impact_origin == "site_transport_impact" ~ "Material transport (to MRF or reuse)",
                                  impact_origin == "EOL_transport_impact" ~ "Material transport (MRF to EOL)",      
                                  impact_origin == "worker_transport" ~ "Worker transport",
                                  impact_origin == "equipment_use" ~ "Equipment use on site",
                                  impact_origin == "total" ~ "Total"))




# table 8 in the main report
carbon_ave_project_table <- filter(gathered__per_home_final_impact, impact_units == "kg CO2e") %>%
   spread(key = "scenario",  value = "impact_value") %>%
   mutate(Difference = Demolition - Deconstruction) %>%
   mutate(Per_SqFt_Difference = Difference/mean(house_weight$house_size)) %>%
   add_column(roworder = c(3,5,1,2,6,4)) %>%
   arrange(roworder) %>%
   select(-impact_origin, -impact_units, -roworder)

# table 9 in the main report
energy_ave_project_table <- filter(gathered__per_home_final_impact, impact_units == "MJ") %>%
   spread(key = "scenario",  value = "impact_value") %>%
   mutate(Difference = Demolition - Deconstruction) %>%
   mutate(Per_SqFt_Difference = Difference/mean(house_weight$house_size)) %>%
   add_column(roworder = c(3,5,1,2,6,4)) %>%
   arrange(roworder) %>%
   select(-impact_origin, -impact_units, -roworder)

kable(carbon_ave_project_table, format.args = list(big.mark = ","), caption = "per house average global warming potential impacts (kg CO2 equivalent)")

kable(energy_ave_project_table, format.args = list(big.mark = ","), caption = "per house average primary energy demand impacts (MJ)")
```


```{r total impact bar plots}

# carbon
ggplot(filter(reshaped_per_home_final_impact, impact_units == "kg CO2e"), aes(x = scenario, y = total, fill = scenario) ) +
   geom_bar(stat = "identity", position = "dodge") +
   geom_hline(yintercept = 0 ) +
   geom_text(aes(label = format(total, digits = 2, big.mark = ",", big.interval = 3L), ), nudge_y = -250, size = 4,  show.legend = F ) +
   scale_fill_manual(values = DEQ_pal[4:5]) + 
   scale_y_continuous(labels = comma ) + 
   labs(x = "", y = "Global Warming Potential (kg CO2e)", fill = "") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "carbon_bar_impact.png", device = "png", path = graph_path, units = "in")

# energy
ggplot(filter(reshaped_per_home_final_impact, impact_units == "MJ"), aes(x = scenario, y = total, fill = scenario) ) +
   geom_bar(stat = "identity", position = "dodge") +
   geom_hline(yintercept = 0 ) +
   geom_text(aes(label = format(total, digits = 2, big.mark = ",", big.interval = 3L), ), nudge_y = -2000, size = 4,  show.legend = F ) +
   scale_fill_manual(values = DEQ_pal[4:5]) + 
   scale_y_continuous(labels = comma ) + 
   labs(x = "", y = "Primary Energy Demand (MJ)", fill = "") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12, face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "energy_bar_impact.png", device = "png", path = graph_path, units = "in")
```


```{r per home impact summary data for activity based bar charts}

carbon_impacts_per_home <- reshaped_per_home_final_impact %>%
   filter(impact_units == "kg CO2e") %>%
   select("scenario", "materials", "material_transport", "worker_transport", "equipment_use") %>%
   gather(`materials`, `material_transport`, `worker_transport`, `equipment_use`, key = "impact_origin", value = "impact_value")

carbon_impacts_per_home$impact_origin <- str_replace_all(carbon_impacts_per_home$impact_origin, "_", " ")

energy_impacts_per_home <- reshaped_per_home_final_impact %>%
   filter(impact_units == "MJ") %>%
   select("scenario", "materials", "material_transport", "worker_transport", "equipment_use") %>%
   gather(`materials`, `material_transport`, `worker_transport`, `equipment_use`, key = "impact_origin", value = "impact_value")

energy_impacts_per_home$impact_origin <- str_replace_all(energy_impacts_per_home$impact_origin, "_", " ")
```


```{r per home impacts by activity bar plots}
# carbon
ggplot(carbon_impacts_per_home, aes(x = reorder(impact_origin, -abs(impact_value) ), y = impact_value, fill = scenario) ) +
   geom_bar(stat = "identity", position = position_dodge(width = 0.95)) +
   geom_hline(yintercept = 0 ) +
   geom_text(aes(label = format(impact_value, digits = 2, big.mark = ",", big.interval = 3L)), position = position_dodge(width = 0.95), vjust = 1, size = 4,  show.legend = F ) +
   scale_fill_manual(values = DEQ_pal[4:5]) + 
   scale_y_continuous(labels = comma ) + 
   labs(x = "", y = "Global Warming Potential (kg CO2e)", fill = "") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "carbon_by_activity.png", device = "png", path = graph_path, units = "in")

# energy
ggplot(energy_impacts_per_home, aes(x = reorder(impact_origin, -abs(impact_value) ), y = impact_value, fill = scenario) ) +
   geom_bar(stat = "identity", position = position_dodge(width = 0.95)) +
   geom_hline(yintercept = 0 ) +
   geom_text(aes(label = format(impact_value, digits = 2, big.mark = ",", big.interval = 3L)), position = position_dodge(width = 0.95), vjust = 1, size = 4,  show.legend = F ) +
   scale_fill_manual(values = DEQ_pal[4:5]) + 
   scale_y_continuous(labels = comma ) + 
   labs(x = "", y = "Primary Energy Demand (MJ)", fill = "") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "energy_by_activity.png", device = "png", path = graph_path, units = "in")
```


5)	CHART THAT SHOWS CONTRIBUTION TO MATERIALS REUSE scenario on an average home.  Which materials contribute most to the salvage benefits?   Do for carbon and energy

```{r materials reuse impacts}
material_reuse_impacts <- project_impact_data %>%
   group_by(scenario, impact_units, SimpleEOLname) %>%
   summarise(material_impact_sum = sum(material_impacts) ) %>%
   filter(material_impact_sum != 0) %>%
   mutate(per_project_material_impact_sum = material_impact_sum/number_of_houses) #%>%
# city_wide is based on the annual total number of demolition projects for that calendar year
#  mutate(city_wide_material_impact_sum = per_project_material_impact_sum * 324)
material_reuse_impacts$SimpleEOLname <- factor(material_reuse_impacts$SimpleEOLname, levels = c('recoverable wood', 'other' , 'nonrecoverable wood', 'metal') )

carbon_material_reuse_impacts <- filter(material_reuse_impacts, impact_units == "kg CO2e") 

energy_material_reuse_impacts <- filter(material_reuse_impacts, impact_units == "MJ") #%>%
   #add_column(roworder = c(1:8)) %>%
   #arrange(desc(roworder))


# carbon impacts
ggplot(carbon_material_reuse_impacts, 
       aes(x = scenario, 
           y = per_project_material_impact_sum, 
           fill = SimpleEOLname)) +
   geom_bar(stat = "identity", 
            position = "stack") +
   geom_hline(yintercept = 0 ) +
   geom_label_repel(aes(label = format(per_project_material_impact_sum, 
                                digits = 2, 
                                big.mark = ",", 
                                big.interval = 3L,
                                min.segment.length = unit(0.2, 'lines'))), 
             size = 3.5, 
             position = position_stack(vjust = 0.5),  
             show.legend = F ) +
   scale_fill_manual(values = DEQ_pal[11:8], 
                     guide = guide_legend(reverse = TRUE)) +
   scale_y_continuous(labels = comma ) +
   labs(x = "", 
        y = "carbon impact (kg CO2e)", 
        fill = "") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12),
         axis.title = element_text(size = 12,face = "bold"),
         legend.position = "top", 
         legend.direction = "horizontal")

ggsave(filename = "carbon_by_material_type.png", device = "png", path = graph_path, units = "in")

# energy impacts
ggplot(energy_material_reuse_impacts, 
       aes(x = scenario, y = per_project_material_impact_sum, fill = SimpleEOLname)) +
   geom_bar(stat = "identity", 
            position = position_stack()) +
   geom_hline(yintercept = 0 ) +
   geom_label_repel(aes(label = format(per_project_material_impact_sum, 
                                digits = 2, 
                                big.mark = ",", 
                                big.interval = 3L,
                                min.segment.length = unit(0.2, 'lines'))), 
             size = 3.5, 
             position = position_stack(vjust = 0.5), 
             show.legend = F ) +
   scale_fill_manual(values = DEQ_pal[11:8], 
                     guide = guide_legend(reverse = TRUE)) + 
   scale_y_continuous(labels = comma ) + 
   labs(x = "", 
        y = "energy impact (MJ)", 
        fill = "") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), 
         axis.title = element_text(size = 12,face = "bold"), 
         legend.position = "top", 
         legend.direction = "horizontal")

ggsave(filename = "energy_by_material_type.png", device = "png", path = graph_path, units = "in")

```

```{r disposition based material impacts}
wood_based_material_reuse_impacts <- project_impact_data %>%
   group_by(scenario, impact_units, disposition, SimpleEOLname) %>%
   summarise(material_impact_sum = sum(material_impacts) ) %>%
   filter(SimpleEOLname != "metal") %>%
   filter(SimpleEOLname != "other") %>%
   filter(material_impact_sum != 0) %>%
   mutate(per_project_material_impact_sum = material_impact_sum/number_of_houses)

carbon_wood_disposition <- filter(wood_based_material_reuse_impacts, impact_units == "kg CO2e")

energy_wood_disposition <- filter(wood_based_material_reuse_impacts, impact_units == "MJ")


ggplot(carbon_wood_disposition, aes(x = scenario, y = per_project_material_impact_sum, fill = disposition)) +
   geom_bar(stat = "identity", position = "stack") +
   geom_hline(yintercept = 0 ) +
   geom_label(aes(label = format(per_project_material_impact_sum, 
                                digits = 2, 
                                big.mark = ",", 
                                big.interval = 3L,
                                min.segment.length = unit(0.2, 'lines'))),
                     size = 3.5, 
                     position = position_stack(vjust = 0.5), 
                     show.legend = F ) +
   scale_y_continuous(labels = comma ) +
   scale_fill_manual(values = c(DEQ_pal[18], DEQ_pal[17], DEQ_pal[16], DEQ_pal[15])) +
   labs(x = "", y = "carbon impact (kg CO2e)", fill = "") +
   facet_grid(. ~ SimpleEOLname) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "carbon_wood.png", device = "png", path = graph_path, units = "in")

ggplot(energy_wood_disposition, aes(x = scenario, y = per_project_material_impact_sum, fill = disposition)) +
   geom_bar(stat = "identity", position = "stack") +
   geom_hline(yintercept = 0 ) +
   geom_label(aes(label = format(per_project_material_impact_sum, 
                                digits = 2, 
                                big.mark = ",", 
                                big.interval = 3L,
                                min.segment.length = unit(0.2, 'lines'))),
                     size = 3.5, 
                     position = position_stack(vjust = 0.5), 
                     show.legend = F ) +
   scale_y_continuous(labels = comma ) +
   scale_fill_manual(values = c(DEQ_pal[18], DEQ_pal[17], DEQ_pal[16], DEQ_pal[15])) +
   labs(x = "", y = "energy impact (MJ)", fill = "") +
   facet_grid(. ~ SimpleEOLname) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "energy_wood.png", device = "png", path = graph_path, units = "in")

metal_other_disposition <- project_impact_data %>%
   group_by(scenario, impact_units, disposition, SimpleEOLname) %>%
   summarise(material_impact_sum = sum(material_impacts) ) %>%
   filter(SimpleEOLname != "recoverable wood") %>%
   filter(SimpleEOLname != "nonrecoverable wood") %>%
   filter(material_impact_sum != 0) %>%
   mutate(per_project_material_impact_sum = material_impact_sum/number_of_houses)

carbon_mo_disposition <- filter(metal_other_disposition, impact_units == "kg CO2e")

energy_mo_disposition <- filter(metal_other_disposition, impact_units == "MJ")
   
ggplot(carbon_mo_disposition, aes(x = scenario, y = per_project_material_impact_sum, fill = disposition)) +
   geom_bar(stat = "identity", position = "stack") +
   geom_text(aes(label = format(per_project_material_impact_sum, digits = 2, big.mark = ",", big.interval = 3L)), size = 3.5, position = position_stack(vjust = 0.5),  show.legend = F ) +
   geom_hline(yintercept = 0 ) +
   scale_fill_manual(values = c(DEQ_pal[17], DEQ_pal[15], DEQ_pal[16])) +
   scale_y_continuous(labels = comma ) +
   labs(x = "scenario", y = "carbon impact (kg CO2e)", fill = "") +
   facet_grid(. ~ SimpleEOLname) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "carbon_mo.png", device = "png", path = graph_path, units = "in")

ggplot(energy_mo_disposition, aes(x = scenario, y = per_project_material_impact_sum, fill = disposition)) +
   geom_bar(stat = "identity", position = "stack") +
   geom_text(aes(label = format(per_project_material_impact_sum, digits = 2, big.mark = ",", big.interval = 3L)), size = 3.5, position = position_stack(vjust = 0.5),  show.legend = F ) +
   geom_hline(yintercept = 0 ) +
   scale_fill_manual(values = c(DEQ_pal[17], DEQ_pal[15], DEQ_pal[16])) +
   scale_y_continuous(labels = comma ) +
   labs(x = "scenario", y = "energy impact (MJ)", fill = "") +
   facet_grid(. ~ SimpleEOLname) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"), legend.position = "top", legend.direction = "horizontal")

ggsave(filename = "energy_mo.png", device = "png", path = graph_path, units = "in")

```


## Correlations
	

The research team was interested in the relationship between the weight of salvaged and disposal materials and the size (square feet) of the house. To explore this in Figure 2 the salvaged materials weight is expressed on the y-axis to the dropbox weight. This is depicted  where the size of the point is relative to the total weight of the house (total salvage weight + dropbox weight), contractors are assigned to the point color, and the median crosshairs have been added to assist in differentiating the better than average performers in the upper left quadrant (with higher salvage weight and lower dropbox weight), from the lower than average performers in the lower right quadrant (lower than average salvage weight and higher dropbox weight.)

```{r ratio of salvage to dropbox weight}
summary(house_weight_US_units)

ggplot(house_weight_US_units, aes(dropbox, salvage, color = contractor, size = house_size)) +
   geom_jitter() +
   #scale_size("house_size (sqft)") +
   geom_text_repel(aes(label = as.integer(percent_salvaged)), seed = 19, show.legend = F) +
   #geom_rug(aes(size = 0.25), sides = "bl", position = "jitter", show.legend = F) +
   geom_vline(xintercept = median(house_weight_US_units$dropbox), color = "grey30" ) +
   geom_hline(yintercept = median(house_weight_US_units$salvage), color = "grey30" ) +
   annotate(geom = "text", x = 54000, y = 9500, label = paste0("median salvage (", median(house_weight_US_units$salvage), " lbs)"), color = "grey30", size = 3) +
   annotate(geom = "text", x = 29700, y = 19000, label = paste0("median disposal (", median(house_weight_US_units$dropbox), " lbs)"), color = "grey30", size = 3) +
   scale_radius("house size (sqft)", range = c(2.5,6.5)) +
   #scale_color_manual(values = DEQ_pal) +
   scale_color_calc() +
   scale_x_continuous(labels = comma ) +
   scale_y_continuous(labels = comma ) +
   labs(x = "dropbox materials (lbs)", y = "salvaged materials (lbs)") +
   theme_tufte() +
   theme(axis.text = element_text(size = 12),
         axis.title = element_text(size = 12,face = "bold"))

ggsave(filename = "ratio_salvage_dropbox.png", width = 9, height = 7, device = "png", path = graph_path, units = "in")
```

# Discussion

# References

*reference EPDs & conversion factor sources here*

Wickham, H. (2016) *ggplot2: Elegant Graphics for Data Analysis*, second edition. Springer. Switzerland.

Wickham, H., Grolemund, G. (2017) *R for Data Science*. O'Reilly Media, Inc. Sebastopol, California.

Xie, Y. (2016) *Dynamic Documents with R and knitr*, second edition. CRC Press, Taylor & Francis Group, LLC. Boca Raton, Florida.


# Appendix

## Supplemental Graphics

```{r house size and salvage yield, fig.cap = "Relation of salvaged material weight to house size"}
ggplot(house_weight_US_units, aes(house_size, salvage)) +
   geom_point( aes(color = contractor), size = 2,  position = "jitter") +
   geom_smooth(method = "glm") +
   scale_color_calc() +
   labs(x = "house size in square feet", y = "salvaged materials (lbs)") +
   scale_x_continuous(labels = comma) +
   scale_y_continuous(labels = comma) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"))

ggsave(filename = "salvage_by_house_size.png", device = "png", path = graph_path, units = "in")
```


```{r house size and dropbox yield, fig.cap = "Relation of disposed material weight to house size"}
ggplot(house_weight_US_units, aes(house_size, dropbox)) +
   geom_point(aes(color = contractor), size = 2,  position = "jitter") +
   geom_smooth(method = "glm") +
   scale_color_calc() +
   labs(x = "house size in square feet", y = "dropbox materials (lbs)") +
   scale_x_continuous(labels = comma) +
   scale_y_continuous(labels = comma) +
   theme_tufte() +
   theme(axis.text = element_text(size = 12), axis.title = element_text(size = 12,face = "bold"))

ggsave(filename = "salvage_by_house_age.png", device = "png", path = graph_path, units = "in")
```

```{r estimated house weight comparison}
ggplot(house_weight_US_units, aes(x = est_weight, y = missing_house_est, color = contractor, size = house_size)) +
   geom_jitter() +
   geom_text_repel(aes(label = as.integer(percent_salvaged)), seed = 19, show.legend = F) +
   geom_hline(yintercept = 0) +
   geom_vline(xintercept = mean(house_weight_US_units$est_weight)) +
   scale_color_calc() + scale_x_continuous(labels = comma ) +
   scale_y_continuous(labels = comma) +
   scale_radius("house size (sqft)", range = c(2,6)) +
   labs(x = "50lbs per sq_ft estimated weight", y = "difference between estimate and calculated weight") +
   theme_tufte() +
   ggtitle("House weight estimates and calculations")

ggsave(filename = "house_weight_estimate_vs_calculation.png", device = "png", path = graph_path, units = "in")


ggplot(house_weight_US_units, aes(x = est_weight, y = percent_missing, color = contractor, size = house_size)) +
   geom_jitter() +
   geom_text_repel(aes(label = as.integer(percent_salvaged)), seed = 19, show.legend = F) +
   geom_hline(yintercept = 0) +
   geom_vline(xintercept = mean(house_weight_US_units$est_weight)) +
   scale_color_calc() + scale_x_continuous(labels = comma ) +
   scale_y_continuous(labels = comma) +
   scale_radius("house size (sqft)", range = c(2,6)) +
   labs(x = "50lbs per sq_ft estimated weight", y = "percentage of house missing from estimated") +
   theme_tufte() +
   ggtitle("House weight estimates and calculations")

ggsave(filename = "house_weight_estimate_vs_percent_missing.png", device = "png", path = graph_path, units = "in")
```


Compute impacts on a sq ft basis.
```{r sq ft based impact contribution breakdown, include = F}
# same as previous code chunk but using sq ft units vs per home units
# reshape impacts for charts
 final_impact_summary <- final_impact_summary %>%
   mutate(per_sq_ft_impact = impact / as.numeric(total_house_size$total_sq_ft) )

reshaped_per_sq_ft_final_impact <- final_impact_summary %>%
   select(c("scenario", "impact_origin", "per_sq_ft_impact", "impact_units")) %>%
   spread(key = impact_origin, value = per_sq_ft_impact) %>%
   rename(materials = material_impacts) %>%
   rename(worker_transport = workers) %>%
   rename(equipment_use = equipment) %>%
   mutate(material_transport = EOL_transport_impact + site_transport_impact) %>%
   mutate(total = materials + material_transport + worker_transport + equipment_use)

# create per sq ft tables for report appendix
carbon_impacts_per_sq_ft <- reshaped_per_sq_ft_final_impact %>%
   filter(impact_units == "kg CO2e") %>%
   gather(`EOL_transport_impact`, `equipment_use`, `materials`, `site_transport_impact`, `worker_transport`, `material_transport`, `total`, key = "impact origin", value = "per_average_home_impact_value") %>%
   spread(key = scenario, value = per_average_home_impact_value) %>%
   mutate(net_impacts = demo - decon) %>%
   select(c("impact origin", "decon", "demo", "net_impacts", "impact_units"))

energy_impacts_per_sq_ft <- reshaped_per_sq_ft_final_impact %>%
   filter(impact_units == "MJ") %>%
   gather(`EOL_transport_impact`, `equipment_use`, `materials`, `site_transport_impact`, `worker_transport`, `material_transport`, `total`, key = "impact origin", value = "per_average_home_impact_value") %>%
   spread(key = scenario, value = per_average_home_impact_value) %>%
   mutate(net_impacts = demo - decon) %>%
   select(c("impact origin", "decon", "demo", "net_impacts", "impact_units"))

kable(carbon_impacts_per_sq_ft, caption = "average carbon impacts per square foot of house")
kable(energy_impacts_per_sq_ft, caption = "average energy impacts per square foot of house")
```


## Assumptions log

```{r assumptions log}
data_description_sheet <- read.csv("data/data_description_sheet.csv")
data_assumptions <- data_description_sheet[97:114, 1]
names(data_assumptions) <- "List of Assumptions"
kable(data_assumptions, caption = "Key data assumptions")
```